<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Create_staffuser extends CI_Controller {
    public function index()
    {
        $this->editStaffuser(-1);
    }
    
    public function editStaffuser($staffuser_id){
        //So user's can't break the login system
        if ($staffuser_id == $this->session->userdata('user_id')){
            $this->session->set_flashdata('staffuser_response','Can\'t edit yourself.');
            redirect(base_url().'settings/manage_staffusers');
            return;
        }
        
        $this->load->model('staffusers');
        $staffuser = $this->staffusers->getByID($staffuser_id);
        
        if ($staffuser != null){
            $title = "Update Staff User";
            $subtitle = $staffuser->staffuser_title;
            $save_text = "Update User";
        }
        else{
            $title = "Create Staff User";
            $subtitle = "";
            $save_text = "Create User";
        }
        
        $data['title'] = $title;
        $data['data'] = array (
            "subtitle" => $subtitle,
            "staffuser" => $staffuser,
            "save_text" => $save_text,
            "password" => generate_password(8, 8)
        ); 
        $data['js'] = array('create_staffuser.js');
        $data['view'] = "settings/view_create_staffuser";
        $this->load->view('view_template',$data);
    }
    
    public function postStaffuser(){
        extract($this->ajax->post("staffuser_id","username","email","name","password","role", "change"));
        
        if ($staffuser_id == $this->session->userdata('user_id')){
            $this->session->set_flashdata('staffuser_response','Can\'t edit yourself.');
            echo json_encode("server");
            return;
        }
        
        $this->load->model("staffusers");
        $this->load->helper('email');
        //validate data        
        $error = array();
        
        if ($this->checkLogin($staffuser_id, $username)){
            $error['login'] = "Username must be unique";
        }
          
        if ($this->checkEmail($staffuser_id, $email)){
            $error['email'] = "Email must be unique"; 
        }
        
        if (!valid_email($email)){
            $error['email'] = 'Email address is invalid';
        }
        
        if (count($error) > 0){
            echo json_encode($error);
            return;
        }
        
        $oldemail = $email;
        if ($staffuser_id > 0){
            try{
                $olduser = $this->staffusers->getByID($staffuser_id);
                $oldemail = $olduser->staffuser_email;
                $username = $olduser->staffuser_login;
            }
            catch(Exception $e){}
        }
        
        if ($change == 0){
            if ($this->staffusers->insertStaffuser($this->session->userdata('role'), $staffuser_id, $username, $email, $name, $role, encrypt_password($password)) === FALSE){
                $this->session->set_flashdata('staffuser_response',"There was an error processing your request.");
                echo json_encode("server");
                send_email_advanced($email, "RMPlanner: Account Created", 
                    "Hello $name,\r\n".
                    "Your user account '$username' has been successfully created.\r\n".
                    "Your password is:\r\n\r\n$password\r\n\r\n".
                    "Remember to change this once you log in\r\n\r\n".
                    "Your current role is ".get_role($role)."\r\n\r\n".
                    "Thankyou,\r\n from all the team at RMPlanner"
                    );
                return;
            }
        }
        else{
            if ($this->staffusers->insertStaffuser($this->session->userdata('role'), $staffuser_id, $username, $email, $name, $role) === FALSE){
                $this->session->set_flashdata('staffuser_response',"There was an error processing your request.");
                echo json_encode("server");
                if ($change != 0){
                send_email_advanced($email, "RMPlanner: Your staff account has been updated", 
                        "Hello,\r\n".
                        "Your staff account '$username' has had it's password reset.\r\n".
                        "Your password is now:\r\n\r\n$password\r\n\r\n".
                        "Remember to change this once you log in\r\n\r\n".
                        "Thankyou,\r\n from all the team at RMPlanner"
                        );
                }
                if ($oldemail != $email){
                    send_email_advanced($oldemail, "RMPlanner: Your email address has changed", 
                        "Hello $name,\r\n".
                        "Your email address for staff account '$username' has changed to '$email'\r\n".
                        "If you believe this is a mistake, please contact an administrator.\r\n\r\n".
                        "Thanks,\r\n from all the team at RMPlanner"
                        );
                }
                return;
            }
        }
        
        
        //Falls through for both if good
        if ($staffuser_id == -1){
            $this->session->set_flashdata('staffuser_response',"Staff user '$username' succesfully created.");
            echo json_encode("good");
        }
        else{
            $this->session->set_flashdata('staffuser_response',"Staff user '$username' succesfully updated.");
            echo json_encode("update");
        }
    }
    
    public function checkLogin($staffuser_id = null, $staffuser_login = null){
        $echo = false;
        //We have an ajax request
        if ($staffuser_id == null || $staffuser_login == null){
            extract($this->ajax->post('staffuser_login','staffuser_id'));
            $echo = true;
        }
        
        $this->load->model('staffusers');
        
        $staffuser = $this->staffusers->getByLogin($staffuser_login);

        $returnString = "good";
        $returnValue = false;
        
        if ($staffuser != null){
            if ($staffuser_login == $staffuser->staffuser_login){
                if ($staffuser_id != $staffuser->staffuser_id){
                    $returnString = "used";
                    $returnValue = true;
                }
            }
        }
        if ($echo){
            echo $returnString;
        }
        else{
            return $returnValue;
        }
    }
    
    public function checkEmail($staffuser_id = null, $staffuser_email = null){
        $echo = false;
        
        //We have an ajax request
        if ($staffuser_id == null || $staffuser_email == null){
            extract($this->ajax->post('staffuser_email','staffuser_id'));
            $this->load->model('staffusers');
            $echo = true;
        }
        
        $staffuser = $this->staffusers->getByEmail($staffuser_email);

        $returnString = "good";
        $returnValue = false;
        
        if ($staffuser != null){
            if ($staffuser_email == $staffuser->staffuser_email){
                if ($staffuser_id != $staffuser->staffuser_id){
                    $returnString = "used";
                    $returnValue = true;
                }
            }
        }
        if ($echo){
            echo $returnString;
        }
        else{
            return $returnValue;
        }
    }
}

